import os

import random

# 用来json对象的序列化和反序列化，主要使用dumps和loads函数
import json

# 导入datetime和timedelta用于日期处理
from datetime import datetime, timedelta

# 导入defaultdict和Counter用于数据结构
from collections import defaultdict, Counter

# 导入random模块用于生成随机数
import random

import math

# 用来管理路径
from pathlib import Path

import random
import itertools

# 常见姓氏（TOP50，按使用频率排序）
surnames = [
    "王",
    "李",
    "张",
    "刘",
    "陈",
    "杨",
    "黄",
    "赵",
    "吴",
    "周",
    "徐",
    "孙",
    "马",
    "朱",
    "胡",
    "林",
    "郭",
    "何",
    "高",
    "罗",
    "郑",
    "梁",
    "谢",
    "宋",
    "唐",
    "许",
    "邓",
    "冯",
    "韩",
    "曹",
    "曾",
    "彭",
    "萧",
    "蔡",
    "潘",
    "田",
    "董",
    "袁",
    "于",
    "余",
    "叶",
    "蒋",
    "杜",
    "沈",
    "姜",
    "范",
    "江",
    "傅",
    "钟",
    "卢",
]

# 男性名字常用字（侧重阳刚、稳重）
male_names = [
    "伟",
    "强",
    "军",
    "峰",
    "涛",
    "明",
    "亮",
    "鹏",
    "杰",
    "浩",
    "宇",
    "博",
    "轩",
    "泽",
    "哲",
    "辰",
    "瑞",
    "帆",
    "航",
    "彬",
    "凯",
    "超",
    "楠",
    "磊",
    "鑫",
    "阳",
    "毅",
    "恒",
    "诚",
    "健",
]

# 女性名字常用字（侧重柔美、雅致）
female_names = [
    "婷",
    "娜",
    "静",
    "丽",
    "敏",
    "芳",
    "娟",
    "艳",
    "玲",
    "燕",
    "菲",
    "琳",
    "琪",
    "雅",
    "雪",
    "梅",
    "雨",
    "欣",
    "梦",
    "悦",
    "彤",
    "曦",
    "妍",
    "茜",
    "颖",
    "瑶",
    "佳",
    "宁",
    "思",
    "语",
]


def generate_names(count=200):
    names = set()  # 用集合避免重复
    while len(names) < count:
        # 随机选姓氏
        surname = random.choice(surnames)
        # 随机确定性别，1:男，2:女
        gender = random.randint(1, 2)
        if gender == 1:
            # 男性双字名：随机选两个男性字
            name = random.choice(male_names) + random.choice(male_names)
        else:
            # 女性双字名：随机选两个女性字
            name = random.choice(female_names) + random.choice(female_names)
        full_name = surname + name
        names.add(full_name)
    return list(names)


# 生成 200 个姓名并打印
if __name__ == "__main__":
    name_list = generate_names(200)
    print("生成的 200 个姓名：")

    # for i, name in enumerate(name_list, 1):
    #     print(f"{i:3d}. {name}")


# 利用生成器生成数据
def generate_user_data():

    while True:
        yield {
            "id": f"A{math.floor(random.random()*100000)}",
            "name": random.choices(name_list),
            "age": random.randint(18, 60),
            "join_date": (
                datetime.now() - timedelta(days=random.randint(0, 365))
            ).strftime("%Y-%m-%d"),
            "score": random.randint(50, 100),
        }


def save_data(filename):
    """
    # 自动生成一份用户信息的测试数据存储到 data 目录下的 users.json 文件中；
    # 读取这份数据，并统计各年龄段人数分布（使用 Counter）；
    # 按照用户分数区间将用户分组（使用 defaultdict）；
    # 可以根据分析结果进一步扩展，比如查找最大/最小分数用户、统计近一年内注册用户等。
    """

    file_path = Path(__file__).parent / filename
    gen = generate_user_data()

    data_json = [next(gen) for i in range(100)]

    with open(file_path, "w", encoding="utf-8") as jsonfile:

        json.dump(data_json, jsonfile, ensure_ascii=False, indent=4)


def read_data(filename):
    file_path = Path(__file__).parent / filename

    with open(file_path, "r", encoding="utf-8") as jsonfile:

        content = json.load(jsonfile)
        return content


# 定义获取年龄范围函数
def get_age_scope(age):
    # 25 20-29 30-39
    start = (age // 10) * 10
    end = start + 9
    return f"{start}-{end}"


# 生成并保存数据
save_data("user_data.json")


def analyze_user_data():
    # 读取数据
    user_data_list = read_data("user_data.json")

    # 用Counter统计所有用户的年龄分布
    # age_distribution = Counter(user["age"] for user in user_data_list)
    # # 输出年龄分布信息
    # print("\n年龄分布:")
    # # 对年龄和人数按年龄从小到大输出
    # for age, count in sorted(age_distribution.items()):
    #     print(f"  {age}岁: {count}人")

    # 根据年龄段分组
    age_groups_list_dict = defaultdict(list)

    for user in user_data_list:
        age_scope = get_age_scope(user["age"])
        age_groups_list_dict[age_scope].append(*user["name"])

    print("age_group_info==", age_groups_list_dict)

    # 用defaultdict按照分数段分组
    score_groups = defaultdict(list)

    for user in user_data_list:
        # 计算分数区间（如70-79）
        score_range = f"{(user['score'] // 10) * 10}-{(user['score'] // 10) * 10 + 9}"
        # 添加用户名到对应分数区间
        score_groups[score_range].append(*user["name"])

    print(score_groups)


analyze_user_data()
